package com.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.library.entity.User;
import com.library.service.UserService;
import com.library.vo.ResultVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理Controller
 *
 * @author Library Team
 */
@Slf4j
@RestController
@RequestMapping("/users")
@PreAuthorize("hasRole('ADMIN')")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
     */
    @GetMapping
    public ResultVO<Page<User>> getUsers(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String realName) {
        try {
            Page<User> page = new Page<>(current, size);
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            if (username != null && !username.isEmpty()) {
                wrapper.like(User::getUsername, username);
            }
            if (realName != null && !realName.isEmpty()) {
                wrapper.like(User::getRealName, realName);
            }
            wrapper.orderByDesc(User::getCreatedAt);

            Page<User> result = userService.page(page, wrapper);

            // 隐藏密码信息
            result.getRecords().forEach(user -> user.setPassword(null));

            return ResultVO.success(result);
        } catch (Exception e) {
            log.error("获取用户列表失败, 错误: {}", e.getMessage());
            return ResultVO.error("获取用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public ResultVO<String> updateUser(@PathVariable Long id, @RequestBody User user) {
        try {
            // 确保路径中的ID与请求体中的ID一致
            user.setId(id);

            boolean result = userService.updateUser(user);
            if (result) {
                log.info("管理员更新用户成功 - ID: {}", id);
                return ResultVO.success("更新成功");
            } else {
                return ResultVO.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户失败 - ID: {}, 错误: {}", id, e.getMessage());
            return ResultVO.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public ResultVO<String> deleteUser(@PathVariable Long id) {
        try {
            boolean result = userService.deleteUser(id);
            if (result) {
                log.info("管理员删除用户成功 - ID: {}", id);
                return ResultVO.success("删除成功");
            } else {
                return ResultVO.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除用户失败 - ID: {}, 错误: {}", id, e.getMessage());
            return ResultVO.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public ResultVO<User> getUserById(@PathVariable Long id) {
        try {
            User user = userService.getById(id);
            if (user != null) {
                // 隐藏密码信息
                user.setPassword(null);
                return ResultVO.success(user);
            } else {
                return ResultVO.error("用户不存在");
            }
        } catch (Exception e) {
            log.error("查询用户失败 - ID: {}, 错误: {}", id, e.getMessage());
            return ResultVO.error("查询失败: " + e.getMessage());
        }
    }
}
